<?php


namespace app\admin\controller;


use app\admin\service\RbacService;
use app\common\controller\CommonController;
use app\common\enum\MainEnum;
use app\common\exception\ParameterFailedException;
use app\common\exception\NotFoundException;
use app\common\model\CouponIssueModel;
use app\common\model\CouponModel;
use app\common\model\CouponProductModel;
use app\common\model\OrderListRefundModel;
use app\common\model\OrderModel;
use app\common\model\ProductModel;
use app\common\model\UserCouponModel;
use app\common\model\UserCouponRecordModel;
use app\common\model\UserModel;
use app\common\service\Lang;
use app\common\validate\CouponValidate;
use think\facade\Db;

class CouponController extends CommonController
{
    public function getProductList()
    {
        $models = (new ProductModel())->field('id,logo_url,name')->select();
        return retJson(Lang::GETDone, $models->toArray());
    }

    public function getCouponList()
    {
        $searchParams = self::getParam([]);
        $where        = [];
        foreach ($searchParams as $key => $value) {
            if (is_array($value) && $key === 'create_time') {
                $where[] = [
                    $key,
                    'between',
                    $value,
                ];
                continue;
            }
            if (strpos($value, '%') !== false) {
                $where[] = [
                    $key,
                    'like',
                    $value,
                ];
            }
            else {
                $where[] = [
                    $key,
                    '=',
                    $value,
                ];
            }
        }
        $where  = [];
        $models = (new CouponModel())->getCouponListPaginate($where, $this->page, $this->limit);
        return retJson(Lang::GETDone, $models->toArray());
    }

    public function getUserCouponList()
    {
        $searchParams = self::getParam([]);
        $where        = [];
        foreach ($searchParams as $key => $value) {
            if (is_array($value) && $key === 'create_time') {
                $where[] = [
                    $key,
                    'between',
                    $value,
                ];
                continue;
            }
            if (strpos($value, '%') !== false) {
                $where[] = [
                    $key,
                    'like',
                    $value,
                ];
            }
            else {
                $where[] = [
                    $key,
                    '=',
                    $value,
                ];
            }
        }
        $where = [];
        $model = (new CouponModel())->with([
            'productsInfo',
        ])->order([
            //            'sea_waybill_number' => 'desc',
            //            'case_number'        => 'desc',
            'create_time' => 'desc',
        ])->where($where)->paginate([
            'page'      => $this->page,
            'list_rows' => $this->limit,
        ]);
        return retJson(Lang::GETDone, $model->toArray());
    }

    public function postCouponAdminGive()
    {

        $params      = self::getParam([
            'coupon_id',
            'coupon_object_type',
        ]);
        (new CouponValidate())->goCheck(__FUNCTION__, $params);
        Db::startTrans();
        try {
            $model = (new CouponModel())->where('id', $params['coupon_id'])->find();
            if (!$model) {
                throw new NotFoundException();
            }
            $userModels  = (new UserModel())->where('group_id', MainEnum::GROUP_USER)->field('id')->select();
            $giveUserIds = [];
            foreach ($userModels->toArray() as $item) {
                $giveUserIds [] = $item['id'];
            }
            switch ($params['coupon_object_type']) {
                case 1:
                    #全部会员
                case 2:
                    #全部会员(没下单的会员)
                    $orderDoneModels = (new OrderModel())->where('status', 'in', [
                        MainEnum::ORDER_STATUS_DONE_BUT_WAIT_APPRAISE,
                        MainEnum::ORDER_STATUS_DONE_AND_APPRAISE,
                    ])->field('user_id')->select();
                    foreach ($orderDoneModels->toArray() as $orderDoneModel) {
                        foreach ($giveUserIds as $key => &$giveUserId) {
                            if ($orderDoneModel['user_id'] === $giveUserId) {
                                unset($giveUserIds[$key]);
                            }
                        }
                    }
                default:
            }
            $prepareUserCouponData       = [];
            $prepareUserCouponRecordData = [];

            foreach ($giveUserIds as $giveUserId) {
                $prepareUserCouponData[]       = [
                    'user_id'    => $giveUserId,
                    'coupon_id'  => $model->getData('id'),
                    'status'     => MainEnum::COUPON_USER_STATUS['待使用'],
                    'start_time' => NOW_TIME,
                    'end_time'   => NOW_TIME + $model->getData('valid_time'),
                ];
                $prepareUserCouponRecordData[] = [
                    'user_id'   => $giveUserId,
                    'coupon_id' => $model->getData('id'),
                    'get_type'  => MainEnum::COUPON_USER_GET_TYPE['管理员赠送'],
                ];
            }
            (new UserCouponModel())->saveAll($prepareUserCouponData);
            (new UserCouponRecordModel())->saveAll($prepareUserCouponRecordData);

            Db::commit();
            return retJson(Lang::POSTDone);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            throw $e;
        }
    }

    public function postCoupon()
    {

        $params      = self::getParam([
            'coupon_name',
            'coupon_use_min_price',
            'coupon_type',
            'coupon_type_jian_price',
            'coupon_type_discount_price',
            'coupon_type_random_min_price',
            'coupon_type_random_max_price',
            'coupon_valid_time',
            'coupon_product_ids',
            'coupon_exchange_integral',
            'coupon_all_product',
            'coupon_issue_status',
            'coupon_issue_time',
            'coupon_issue_total_count',
            'coupon_issue_single_limit',
        ]);
        (new CouponValidate())->goCheck(__FUNCTION__, $params);
        Db::startTrans();
        try {
            if ($params['coupon_issue_status'] === true) {
                if (!$params['coupon_issue_time']) {
                    throw new ParameterFailedException();
                }
                if ($params['coupon_issue_total_count'] === null) {
                    throw new ParameterFailedException();
                }
                if ($params['coupon_issue_single_limit'] === null) {
                    throw new ParameterFailedException();
                }
            }
            if ($params['coupon_all_product'] !== true) {
                if (!$params['coupon_product_ids']) {
                    throw new ParameterFailedException();
                }
                $productModels = (new ProductModel())->where('id', 'in', $params['coupon_product_ids'])
                    ->field('id')
                    ->select();
                if (count($productModels) !== count($params['coupon_product_ids'])) {
                    throw new ParameterFailedException();
                }
            }
            //            'coupon_product_ids',
            //            'coupon_all_product',
            $model                    = new CouponModel();
            $model->name              = $params['coupon_name'];
            $model->use_min_price     = $params['coupon_use_min_price'];
            $model->type              = $params['coupon_type'];
            $model->exchange_integral = $params['coupon_exchange_integral'];
            $model->valid_time        = $params['coupon_valid_time'];
            $model->all_product       = $params['coupon_all_product'];
            $model->issue_status      = $params['coupon_issue_status'];
            if ($params['coupon_issue_status'] == true) {
                $model->issue_total_count  = $params['coupon_issue_total_count'];
                $model->issue_start_time   = $params['coupon_issue_time'][0];
                $model->issue_end_time     = $params['coupon_issue_time'][1];
                $model->issue_single_limit = $params['coupon_issue_single_limit'];
            }
            switch ($params['coupon_type']) {
                case MainEnum::COUPON_TYPE['满减']:
                    if (!$params['coupon_type_jian_price']) {
                        throw new ParameterFailedException();
                    }
                    $model->type_jian_price = $params['coupon_type_jian_price'];
                    break;
                case MainEnum::COUPON_TYPE['折扣']:
                    if (!$params['coupon_type_discount_price']) {
                        throw new ParameterFailedException();
                    }
                    $model->type_discount_price = $params['coupon_type_discount_price'];
                    break;
                case MainEnum::COUPON_TYPE['随机减金额']:
                    if (!$params['coupon_type_random_min_price']) {
                        throw new ParameterFailedException(['msg' => '随机减属性错误']);
                    }
                    if (!$params['coupon_type_random_max_price']) {
                        throw new ParameterFailedException(['msg' => '随机减属性错误']);
                    }
                    if ($params['coupon_type_random_min_price'] >= $params['coupon_type_random_max_price']) {
                        throw new ParameterFailedException(['msg' => '随机减属性错误']);
                    }
                    $model->type_random_min_price = $params['coupon_type_random_min_price'];
                    $model->type_random_max_price = $params['coupon_type_random_max_price'];
                    break;
            }
            $model->save();

            if ($params['coupon_all_product'] !== true) {
                $prepareCouponProductData = [];
                foreach ($productModels as $productModel) {
                    $prepareCouponProductData[] = [
                        'product_id' => $productModel->getData('id'),
                        'coupon_id'  => $model->getData('id'),
                    ];
                }
                $couponProductModels = (new CouponProductModel())->where('coupon_id', $model->getData('id'))->select();
                foreach ($couponProductModels as $item) {
                    $item->delete();
                }
                (new CouponProductModel())->saveAll($prepareCouponProductData);
            }

            Db::commit();
            return retJson(Lang::POSTDone);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            throw $e;
        }
    }

    public function putCoupon()
    {

        $params      = self::getParam([
            'coupon_id',
            'coupon_name',
            'coupon_use_min_price',
            'coupon_type',
            'coupon_type_jian_price',
            'coupon_type_discount_price',
            'coupon_type_random_min_price',
            'coupon_type_random_max_price',
            'coupon_valid_time',
            'coupon_product_ids',
            'coupon_exchange_integral',
            'coupon_all_product',
            'coupon_issue_status',
            'coupon_issue_time',
            'coupon_issue_total_count',
            'coupon_issue_single_limit',
        ]);
        (new CouponValidate())->goCheck(__FUNCTION__, $params);
        Db::startTrans();
        try {
            if ($params['coupon_issue_status'] === true) {
                if (!$params['coupon_issue_time']) {
                    throw new ParameterFailedException(['msg' => '时间错误']);
                }
                if ($params['coupon_issue_total_count'] === null) {
                    throw new ParameterFailedException();
                }
                if ($params['coupon_issue_single_limit'] === null) {
                    throw new ParameterFailedException();
                }
            }
            if ($params['coupon_all_product'] !== true) {
                if (!$params['coupon_product_ids']) {
                    throw new ParameterFailedException();
                }
                $productModels = (new ProductModel())->where('id', 'in', $params['coupon_product_ids'])
                    ->field('id')
                    ->select();
                if (count($productModels) !== count($params['coupon_product_ids'])) {
                    throw new ParameterFailedException();
                }
            }
            $model = (new CouponModel())->where('id', $params['coupon_id'])->find();
            if (!$model) {
                throw new NotFoundException();
            }
            $model->name              = $params['coupon_name'];
            $model->use_min_price     = $params['coupon_use_min_price'];
            $model->type              = $params['coupon_type'];
            $model->exchange_integral = $params['coupon_exchange_integral'];
            $model->valid_time        = $params['coupon_valid_time'];
            $model->all_product       = $params['coupon_all_product'];
            $model->issue_status      = $params['coupon_issue_status'];
            if ($params['coupon_issue_status'] == true) {
                $model->issue_total_count  = $params['coupon_issue_total_count'];
                $model->issue_start_time   = $params['coupon_issue_time'][0];
                $model->issue_end_time     = $params['coupon_issue_time'][1];
                $model->issue_single_limit = $params['coupon_issue_single_limit'];
            }
            switch ($params['coupon_type']) {
                case MainEnum::COUPON_TYPE['满减']:
                    if (!$params['coupon_type_jian_price']) {
                        throw new ParameterFailedException();
                    }
                    $model->type_jian_price = $params['coupon_type_jian_price'];
                    break;
                case MainEnum::COUPON_TYPE['折扣']:
                    if (!$params['coupon_type_discount_price']) {
                        throw new ParameterFailedException();
                    }
                    $model->type_discount_price = $params['coupon_type_discount_price'];
                    break;
                case MainEnum::COUPON_TYPE['随机减金额']:
                    if (!$params['coupon_type_random_min_price']) {
                        throw new ParameterFailedException(['msg' => '随机减属性错误']);
                    }
                    if (!$params['coupon_type_random_max_price']) {
                        throw new ParameterFailedException(['msg' => '随机减属性错误']);
                    }
                    if ($params['coupon_type_random_min_price'] >= $params['coupon_type_random_max_price']) {
                        throw new ParameterFailedException(['msg' => '随机减属性错误']);
                    }
                    $model->type_random_min_price = $params['coupon_type_random_min_price'];
                    $model->type_random_max_price = $params['coupon_type_random_max_price'];
                    break;
            }
            $model->save();
            $prepareCouponProductData = [];
            if ($params['coupon_all_product'] !== true) {
                foreach ($productModels as $productModel) {
                    $prepareCouponProductData[] = [
                        'product_id' => $productModel->getData('id'),
                        'coupon_id'  => $model->getData('id'),
                    ];
                }
                $couponProductModels = (new CouponProductModel())->where('coupon_id', $model->getData('id'))->select();
                foreach ($couponProductModels as $item) {
                    $item->delete();
                }
                (new CouponProductModel())->saveAll($prepareCouponProductData);
            }

            Db::commit();
            return retJson(Lang::PUTDone);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            throw $e;
        }
    }

    public function deleteCoupon()
    {

        $params      = self::getParam(['coupon_id']);
        (new CouponValidate())->goCheck(__FUNCTION__, $params);
        Db::startTrans();
        try {
            if ($params['coupon_issue_status'] === true) {
                if (!$params['coupon_issue_time']) {
                    throw new ParameterFailedException();
                }
                if (empty($params['coupon_issue_total_count'])) {
                    throw new ParameterFailedException();
                }
            }
            $model = (new CouponModel())->where('id', $params['coupon_id'])->find();
            if (!$model) {
                throw new NotFoundException();
            }

            $userCouponModel = UserCouponModel::where('id', $params['coupon_id'])->find();
            if ($userCouponModel) {
                throw new ParameterFailedException(['msg' => '某用户含有该优惠券，无法删除']);
            }

            $couponIssueModel = (new CouponIssueModel())->where('coupon_id', $model->getData('id'))->find();
            if ($couponIssueModel) {
                throw new ParameterFailedException(['msg' => '该优惠券在首页发放中，无法删除']);
            }

            $model->delete_time = NOW_TIME;
            $model->save();

            Db::commit();

            return retJson(Lang::DELETEDone);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            throw $e;
        }
    }
}